<template>
	<view class="h-fill">
		<map class="top-fixed map"
		 :style="{height: mapHeight + 'px'}"
		 :controls="controls" 
		 :markers="markers" 
		 :include-points="markers" 
		 :show-location="true"
		 @controltap="handleControlTap"
		 @markertap="handleMarkerTap"
		 :longitude="centerLocation.longitude"
		 :latitude="centerLocation.latitude"
		 ></map>
		<!-- <uni-fab :showIcon="false" direction="vertical" horizontal="right" vertical="top" :content="categories" @trigger="handleCategoryChange"></uni-fab> -->
		<view v-show="!popupVisible" class="bot-fixed content bg-white round-corner" @click="open">
			<view class="btn-popup uni-flex uni-column justify-center align-center">
				<uni-icons color="#ffffff" type="arrowup"></uni-icons>
			</view>
		</view>
		<view class="popup content" v-show="popupVisible" :style="{height: popupHeight + 'px'}">
			<uni-transition @change="handleChange" :mode-class="ani" :styles="transClass" :duration="duration" :show="showTrans">
				<view class="popup-content v-fill v-box">
					<view class="btn-popup uni-flex uni-column align-center justify-center h-fill" style="background-color: #F5F5F5;" @click="close">
						<uni-icons color="#333333" type="arrowdown"></uni-icons>
					</view>
					<view class="l-pad r-pad b-pad h-fill" :style="{height: scrollViewHeight + 'px'}">
						<scroll-view :scroll-into-view="selectedItem" v-if="list.length" :scroll-y="true" class="h-fill v-fill" :scroll-with-animation="true">
							<view :id="'item_' + index" @click="navToDetail(index)" v-for="(item, index) in list" :key="item.id" class="list-item round-corner uni-flex uni-column">
								<view class="uni-flex align-center pad">
									<u-lazy-load :borderRadius="20" class="list-item-logo" loading-img="/static/easy-loadimage/loading.gif"
										error-img="/static/easy-loadimage/loadfail.png" 
										:image="item.photos[0] || $getCloudStorageUrl('/logo.jpg')" :height="160" img-mode="aspectFill"></u-lazy-load>
									<view class="uni-flex-extend uni-ellipsis">
										<view class="uni-flex align-center">
											<text class="list-item-title uni-flex-extend uni-ellipsis">{{item.name}}</text>
											<u-tag v-if="item.category" :text="item.category" shape="circle"
												bgColor="rgba(9, 129, 255, 0.2)" :color="item.color || '#7C6CEE'" borderColor="rgba(9, 129, 255, 0.2)"></u-tag>
										</view>
										<view class="uni-flex align-center uni-text-gray" style="padding: 6rpx 0;">
											<image class="list-item-img" mode="aspectFit" src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_dingwei_juli@2x.png"></image>
											<text v-if="item.distance" class="list-item-distance">{{item.distanceDes}}</text>
											<view class="list-item-seprator" v-if="item.distance && item.address"></view>
											<text class="uni-flex-extend uni-ellipsis" v-if="item.address">{{item.address}}</text>
										</view>
										<view class="uni-flex align-center">
											<view class="uni-flex-extend uni-flex align-center">
												<image @click.stop="navToLocation(index)" class="list-item-act" mode="aspectFit" src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_dingwei@2x.png"></image>
												<image v-if="item.phone" @click.stop="makePhoneCall(index)" mode="aspectFit" class="list-item-act" src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_dianhua@2x.png"></image>
											</view>
											<text class="uni-text-gray">服务次数：{{item.remainTimes || 0}}/{{item.serviceTimes || 0}}</text>
										</view>
									</view>
								</view>
								<u-line></u-line>
								<view class="pad uni-flex align-center">
									<image class="text-icon" src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_liwu@2x.png" mode="aspectFit"></image>
									<view class="uni-flex-extend uni-ellipsis" style="color: #D89D4D;">{{item.serviceContent}}</view>
								</view>
							</view>
						</scroll-view>
						<uni-load-more v-else :status="loadingStatus"></uni-load-more>
					</view>
				</view>
			</uni-transition>
		</view>
	</view>
</template>

<script>
	import {mapState} from 'vuex';
	import {getColor} from "../../common/colorUtil.js"
	import {
		getServiceList
	} from "../../api/platform/store.js"
	var sysInfo;
	export default {
		name: "service-list",
		data() {
			return {
				list: [],
				loadingStatus: 'noMore',
				centerLocation: {},
				markers: [],
				controls: [],
				mapHeight: 600,
				popupHeight: 300,
				navHeight: 44,
				scrollViewHeight: 0,
				popupVisible: true,
				showTrans: true,
				transClass: {
					'position': 'fixed',
					'left': 0,
					'right': 0,
				},
				duration: 300,
				ani: ['slide-bottom'],
				// categories: [],
				// selectedCategoryIdx: -1,
				imageStyle: {
					'border-radius': '20rpx'
				},
				selectedItem: ""
			}
		},
		props: {
			level: {
				type: Number,
				default: -1
			},
			loadRemainTimes: {
				type: Boolean,
				default: false
			},
			categoryId: {
				type: String,
				default: ''
			}
		},
		computed: {
			...mapState(['hasLogin'])
		},
		watch: {
			level(newVal) {
				this.loadData();
			},
			categoryId(newVal) {
				// this.updateSelectedCategory();
				this.loadData();
			}
		},
		created() {
			sysInfo = uni.getSystemInfoSync();
			//#ifdef MP
				let rect = uni.getMenuButtonBoundingClientRect();
				this.navHeight = (rect.top - sysInfo.statusBarHeight) * 2 + rect.height;
			//#endif
			this.mapHeight = sysInfo.windowHeight - sysInfo.statusBarHeight - this.navHeight;
			this.popupHeight = sysInfo.windowHeight * 0.5;
			this.scrollViewHeight = this.popupHeight - 35 - sysInfo.safeAreaInsets.bottom
			this.updateControls();
			this.updateCenterLocation();
			// this.popupVisible = false;
		},
		mounted() {
			this.loadData();
		},
		methods: {
			handleCategoryChange(e) {
				this.$log("category changed", e);
				if (this.selectedCategoryIdx === e.index) {
					return;
				}
				if (this.selectedCategoryIdx != -1) {
					this.categories[this.selectedCategoryIdx].active = false;
				}
				this.categories[e.index].active = true;
				this.selectedCategoryIdx = e.index;
				this.reloadServices();
			},
			navToDetail(idx) {
				this.$emit("itemClick", this.list[idx]);
			},
			navToLocation(idx) {
				let item = this.list[idx]
				uni.openLocation({
					latitude: item.location.coordinates[1],
					longitude: item.location.coordinates[0],
					address: item.address || '',
					success: (res) => {
						this.$log("打开地图查看位置成功", res);
					},
					fail: (err) => {
						this.$log("打开地图查看位置失败", err);
					}
				})
			},
			makePhoneCall(idx) {
				let item = this.list[idx]
				// #ifndef H5
				uni.makePhoneCall({
					phoneNumber: item.phone,
				})
				// #endif
			},
			updateCenterLocation() {
				uni.getLocation({
					type: "gcj02",
					success: (res) => {
						this.centerLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						}
					},
					fail: (err) => {
						this.$log("获取位置失败", err);
            this.centerLocation = uni.getStorageSync('userLocation')
					}
				})
			},
			handleControlTap(e) {
				this.$log("control tapped", e);
				if (e.controlId === "backLocation") {
					this.updateCenterLocation();
				}
			},
			handleMarkerTap(e) {
				this.$log("marker tapped", e);
				let idx = e.detail.markerId;
				if (!this.popupVisible) {
					this.open()
					setTimeout(() => {
						this.selectedItem = `item_${idx}`;
					}, 500);
				} else {
					this.selectedItem = `item_${idx}`;
				}
			},
			updateControls() {
				this.$nextTick(() => {
					this.controls = [];
					var top = this.mapHeight - 70;
					this.$log("control top", top);
					this.controls.push({
							id: 'backLocation',
							iconPath: "/static/img/ic_back-location.png",
							position: {
								top: top,
								width: 30,
								height: 30
							},
							clickable: true
						});
				})
			},
			handleChange(e) {
				if (e.detail) {
					this.mapHeight = sysInfo.windowHeight - sysInfo.statusBarHeight - this.navHeight - this.popupHeight + 35;
					this.updateControls();
				}
			},
			open() {
				this.popupVisible = true
				this.$nextTick(() => {
					clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						this.showTrans = true
					}, 50);
				})
			},
			close(type) {
				this.showTrans = false
				this.mapHeight = sysInfo.windowHeight - sysInfo.statusBarHeight - this.navHeight;
				this.popupVisible = false
				this.updateControls();
				this.$nextTick(() => {
					clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						this.$emit('change', {
							show: false
						})
					}, 300)
				})
			},
			formatDistance(meters) {
				if (meters < 1000) {
					return `${Math.floor(meters)}m`;
				} else {
					return `${Math.floor(meters / 1000)}km`;
				}
			},
			async reloadServices() {
				if (this.loadingStatus === "loading") {
					return;
				}
				if (!this.userLocation) {
					let [err, res] = await uni.getLocation({
						type: "gcj02"
					})
					console.log('location', res, err)
          if (err) {
            res = uni.getStorageSync('userLocation')
          }
					this.userLocation = {
						longitude: res.longitude,
						latitude: res.latitude
					}
				}
				this.markers = [];
				this.list = [];
				this.loadingStatus = "loading";
				var query = {
					city: uni.getStorageSync('currentRegion').city.value,
				}
				if (this.userLocation) {
					query.userLocation = this.userLocation
				}
				if (this.level > 0) {
					query.level = this.level;
				}
				// if (this.selectedCategoryIdx != -1) {
				// 	query.categoryId = this.categories[this.selectedCategoryIdx].id;
				// }
				if (this.categoryId) {
					query.categoryId = this.categoryId;
				}
				try{
					let records = await getServiceList(query);
					if (records.length) {
						// try{
						// 	if (this.loadRemainTimes && this.hasLogin) {
						// 		let ids = records.map(item => { return item.id; });
						// 		let res1 = await this.$http.getRemainServiceTimes(ids);
						// 		var i = 0;
						// 		records.forEach(item => {
						// 			item.remainTimes = res1[i++];
						// 		});
						// 	}
						// }catch(e){}
						records.forEach((item) => {
							item.color = getColor(item.category);
							item.distanceDes = this.formatDistance(item.distance);
						});
						this.list = this.list.concat(records);
						this.markers = this.markers.concat(records.map((item, idx) => {
							return {
								id: idx,
								longitude: item.location.coordinates[0],
								latitude: item.location.coordinates[1],
								callout: {
									content: item.name,
									borderRadius: 10,
									padding: 10
								}
							}
						}));
						// this.$log("商家标记", this.markers);
					}
					this.loadingStatus = "noMore";
				}catch(e){
					this.$log("获取商家列表遇到错误", e);
					this.loadingStatus = "noMore";
					throw e;
				}
			},
			// updateSelectedCategory() {
			// 	for (var i = 0; i < this.categories.length; i++) {
			// 		if (this.categoryId === this.categories[i].id) {
			// 			this.selectedCategoryIdx = i;
			// 			break;
			// 		}
			// 	}
			// },
			// async reloadCategories() {
			// 	try{
			// 		let data = await this.$http.getServiceCategorys();
			// 		this.$log("当前分类", this.categoryId);
			// 		this.categories = data.records.map((item, idx) => {
			// 			item.text = item.name;
			// 			item.active = this.categoryId === item.id;
			// 			item.iconPath = item.icon;
			// 			item.selectedIconPath = item.icon;
			// 			return item;
			// 		});
			// 		this.$log("分类列表", this.categories);
			// 		this.updateSelectedCategory();
			// 	}catch(e){
			// 		this.$log("加载商家分类遇到错误", e);
			// 		throw e;
			// 	}
			// },
			async loadData() {
				try{
					// await this.reloadCategories();
					await this.reloadServices();
				}catch(e){
					
				}
			}
		}
	}
</script>

<style lang="scss">
	.map {
		width: 750rpx;
		// height: 500rpx;
	}
	.popup {
		&-content {
			border-top-left-radius: 30px;
			border-top-right-radius: 30rpx;
		}
		border-top-left-radius: 26rpx;
		border-top-right-radius: 26rpx;
		background-color: #F5F5F5;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 300px;
		z-index: 999;
	}
	.list-item {
		background-color: #FFFFFF;
		&-logo {
			width: 210rpx;
			height: 160rpx;
			margin-right: 20rpx;
		}
		&-title {
			font-size: 30rpx;
			font-weight: bold;
			margin-right: 20rpx;
		}
		&-times {
			font-size: 24rpx;
			color: #656565;
		}
		&-distance {
			font-size: 24rpx;
		}
		&-seprator {
			width: 1px;
			height: 20rpx;
			background-color: #999999;
			margin: 0 10rpx;
		}
		&-area {
			font-size: 24rpx;
		}
		&-img {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10rpx;
		}
		&-act {
			width: 46rpx;
			height: 46rpx
		}
		&-act:not(:last-child) {
			margin-right: 40rpx;
		}
		&-content {
			color: #353535;
			font-size: 22rpx;
			color: #ff8163;
			font-weight: bold;
			max-width: 280rpx;
		}
		&-line {
			height: 1rpx;
			background-color: #DDDDDD;
		}
		&-imgs {
			white-space: nowrap;
			height: 160rpx;
			&-img {
				display: inline-block;
				width: 210rpx;
				height: 160rpx;
			}
			&-img:not(:last-child) {
				margin-right: 4rpx;
			}
		}
	}
	.list-item:not(:last-child) {
		margin-bottom: 20rpx;
	}
	.btn-popup {
		background-color: #D61719;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		height: 35px;
	}
</style>
